package jdbc;

import utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;


public class AcidDemo {
    public static void main(String[] args) throws Exception {
        acidTest(19);
    }

    public static void acidTest(int num) throws Exception {
        Connection conn = null;
        Statement st = null;
        Savepoint sp = null;

        try {
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false); // 打开事务

            st = conn.createStatement();
            st.executeUpdate("UPDATE user SET address='湖南' WHERE id=1");

            sp = conn.setSavepoint();
            if (num > 9){
                throw new RuntimeException();}

            st.executeUpdate("UPDATE user SET address='sichuan' WHERE id=10");
            conn.commit(); // 提交事务

        }catch (SQLException e) {
            throw new RuntimeException("语法错误");
        }catch (RuntimeException e) {
            if (conn != null && sp !=null){
                try {
                    conn.rollback(sp);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            throw new RuntimeException("测试错误");
        }finally {
            JdbcUtils.free(st, conn, null);
        }
    }
}
